/**
 * getToken  获取token
 * 
 */

/**
 * Created by  lizhihang
 */

var express = require('express');
var router = express.Router();
var logger = require('../logger');
var superagent = require('superagent');
var mongo = require('mongoskin');
var jwt = require('jsonwebtoken');
var http = require('http');
var fs = require('fs');
var request = require('request');
var redis = require("redis");
var yzmService = require("./yzmService");
var client = redis.createClient(6379, "127.0.0.1");


var db = mongo.db("mongodb://localhost:27017/weGDUT");
db.bind('weGDUT');




function bind(req, res, next) {
  var token = req.body.token;
  var username = req.body.username;
  var password = req.body.password;

  //  var { token, username, password } = req.body
  // console.log(req.body)

  if (token && username && password) {
    //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
    try {
      let decoded = jwt.verify(token, 'thefirstminappofvtmer');
      // console.log(decoded)
      var openid = decoded.openid;
      //查找数据库中是否已经绑定
      var result = new Promise((resolve, reject) => {
        db.weGDUT.find({
          openid: openid
        }).toArray(function (err, items) {
          resolve(items)
        })
      })
      var users
      result.then(function (value) {
        users = value[0]
        if (users.username) {
          //   //先从redis取cookie
          //   var cookie = getCookieFromRedis(users.username)
          //   cookie.then(function(cookie){
          //带cookie请求教务系统
          toCheckIfAccess(username, password).then(function (value) {
            if (value.status === 0) {
              db.weGDUT.update({
                openid: openid
              }, {
                $set: {
                  username: username,
                  password: password
                }
              })
              var token = jwt.sign(users, 'thefirstminappofvtmer');
              res.send({
                code: 200,
                message: 'change bind succeed',
                data: token
              })
            } else {
              res.send({
                code: 500,
                message: 'student account can not access to the school system'
              })
            }
          })
        } else {
          //未找到该用户，未绑定，下面进行绑定操作
          toCheckIfAccess(username, password).then(function (value) {
            if (value.code === 0) {
              //顺利通过学校新教务系统的认证，可以进行写入数据库以及进行绑定操作，返回新的 token
              //TODO redis存用户cookie
              yzmService.setCookieIntoRedis(username, value.cookie)
              //如果数据库没有任何相关信息
              if (!users.openid) {
                let userInfo = {
                  'openid': openid,
                  'username': username,
                  'password': password
                }
                db.weGDUT.insert(userInfo)
                var newToken = jwt.sign(userInfo, 'thefirstminappofvtmer');
                res.send({
                  code: 200,
                  message: 'success',
                  data: newToken
                })
              } else { //如果数据库只有openid 没有username 和 password
                db.weGDUT.update({
                  openid: openid
                }, {
                  $set: {
                    username: username,
                    password: password
                  }
                })
                var newToken = jwt.sign(users, 'thefirstminappofvtmer');
                res.send({
                  code: 200,
                  message: 'success',
                  data: newToken
                })
              }
            } else {
              res.send({
                code: 500,
                message: 'student account can not access to the school system'
              })
            }
          })
        }
      })
    } catch (err) {
      res.send({
        code: 401,
        message: 'token invid' + err
      })
    }
  } else {
    res.send({
      code: 404,
      message: 'token or username or password can not be null, To bind the account'
    })
  }
}

function login(req, res, next) {
  // var token = req.body.token;
  var username = req.body.username;
  var password = req.body.password;
  var yzm = req.body.yzm;
  var cookie = req.body.cookie;

  //  var { token, username, password } = req.body
  // console.log(req.body)

  if ( /*token &&*/ username && password && yzm && cookie) {
    //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
    //  try {
    //let decoded = jwt.verify(token, 'thefirstminappofvtmer');
    //console.log(decoded)
    // var openid = decoded.openid;
    var result = toCheckIfAccess(username, password, yzm, cookie);
    result.then(function (value) {
      if (value == 0) {
        //yzmService.setCookieIntoRedis(username,cookie)
        //var userInfo = new Promise((resolve, reject) => {
        // db.weGDUT.find({ username: username }).toArray(function (err, items) {
        //  resolve(items)
        //})
        //})
        //var users
        //userInfo.then(function(value){
        //users = value[0]
        //console.log('test:'+users)
        // if(users.name){
        //   var token = jwt.sign(users, 'thefirstminappofvtmer')
        //   console.log('test:'+token)
        //  res.send({ code:200, message:'ok',"data":{cookie:cookie, token:token } })
        // }else{
        //查找数据库中是否已经绑定
        var check = new Promise((resolve, reject) => {
          db.weGDUT.find({
            username: username
          }).toArray(function (err, items) {
            resolve(items)
          })
        })
        if (!check.username) {
          var users = {
            "username": username,
            "password": password
          }
          yzmService.setCookieIntoRedis(username, cookie)
          db.weGDUT.insert(users)
          var token = jwt.sign(users, 'thefirstminappofvtmer')
          // console.log('test:' + token)
          // console.log(cookie)
          res.send({
            code: 200,
            message: 'ok',
            "data": {
              "cookie": cookie,
              "token": token
            }
          })
        } else {
          db.weGDUT.update({
            username: username
          }, {
            $set: {
              username: username,
              password: password
            }
          })
          var newToken = jwt.sign(check, 'thefirstminappofvtmer');
          res.send({
            code: 200,
            message: 'success',
            data: newToken
          })
        }

        // }}
      } else {
        res.send({
          code: 500,
          message: '登录失败，验证码错误或密码错误'
        })
      }
    })
    //  } catch (err) {
    //   res.send({ code: 401, message: 'token invid' + err })
    // }
  } else {
    res.send({
      code: 402,
      message: '缺少参数'
    })
  }
}

function toCheckIfAccess(username, password, yzm, cookie) {
  return new Promise((resolve, reject) => {
    const baseUrl = 'http://jxfw.gdut.edu.cn/new/login'
    let formData = {
      account: username, //'3114006472'
      pwd: password, //'472040743lzh'
      verifycode: yzm,
    }
    // console.log(formData)
    superagent.post(baseUrl)
      .set("Cookie", cookie)
      .type("form")
      .send(formData)
      .end(function (err, res) {
        if (err) {
          reject(err);
        };
        let result = JSON.parse(res.text)
        if (result.code == 0) {
          // console.log('result' + result.code)

          resolve(result.code)
        } else {
          // console.log(result);
          console.log('fail to login:' + username)
          resolve(1)
        }
      }) //post end函数
  }) //return
}

module.exports = {
  bind,
  login
};